package com.zp.datax.core.util;

import lombok.Cleanup;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * prop util
 *
 * @author xuxueli 2018-02-23 21:57:05
 */
public class PropUtil {
    private static Logger logger = LoggerFactory.getLogger(PropUtil.class);

    /**
     * load prop
     *
     * @param propertyFileName disk path when start with "file:", other classpath
     * @return
     */
    @SneakyThrows
    public static Properties loadProp(String propertyFileName) {

        // load file location, disk
        File file = new File(propertyFileName);
        if (!file.exists()) {
            return null;
        }
        URL url = new File(propertyFileName).toURI().toURL();
        @Cleanup
        InputStream in = new FileInputStream(url.getPath());
        if (in == null) {
            return null;
        }

        Properties prop = new Properties();
        prop.load(new InputStreamReader(in, StandardCharsets.UTF_8));

        return prop;
    }

    /**
     * write prop to disk
     *
     * @param properties
     * @param filePathName
     * @return
     */
    @SneakyThrows
    public static boolean writeProp(Properties properties, String filePathName) {
        // mk file
        File file = new File(filePathName);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }

        // write data
        @Cleanup
        FileOutputStream fileOutputStream = new FileOutputStream(file, false);
        properties.store(new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8), null);
        return true;

    }

}
